<script setup lang="ts">
import { state, clearItems, addAssetItemByDraft, addSpareItemByDraft } from '../state';
import { onMounted, onBeforeUnmount, watch, nextTick, computed } from 'vue';
import AssetTypeForm from '../components/asset-type-form.vue';
import SelectSpare from '../select-spare.vue';
import ApproveProcessList from '../../../../approve/edit/components/approve-process-list/approve-process-list.vue';
import { showToast, navigateTo, showLoading, getCurrentInstance, showModal } from '@tarojs/taro';
import { ADD_FP_ASSET_REPAIR_RECORD_REQ } from '/@/api/modules/flow-path/flow-path-repair';
import {
  QUERY_FTD_FOR_ADD_FLOW,
  QUERY_FLOW_BY_COND_ATTR,
} from '/@/api/modules/flow-path/flow-path-template';
import { FIND_ONE, SAVE, DELETE } from '/@/api/modules/flow-path/flow-path-draft';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { QUERY_APP_FLOW_PATH_RECORD_DETAIL } from '/@/api/modules/flow-path/flow-path';
import { QUERY_FPR_PRODUCT_LIST_REQ } from '/@/api/modules/flow-path/flow-path-product';
import { QUERY_FLOW_PATH_TEMPLATE_CONTRACT } from '/@/api/modules/flow-path/flow-path-template-contract';
/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as unknown as {
  templateCode: string;
  /**
   * 审批id
   */
  id?: string;
};

/**
 * 耗材类型
 * true: 表格全部类容已经填写，false：还有表格字段没填写
 */
function checkSpareForm() {
  /**
   * resultList: 填写类容为true，没填写为false
   */
  const resultList: boolean[] = [];
  state.spareList.forEach((item) => {
    //耗材名称
    resultList.push(item.productName && item.productName?.length > 0 ? true : false);
    //耗材规格名称
    resultList.push(item.productSpecName && item.productSpecName?.length > 0 ? true : false);
    //耗材数量
    resultList.push(item.quantity && item.quantity > 0 ? true : false);
  });
  //校验每个字段都不空
  return resultList.every((item) => {
    return item;
  });
}
//根据耗材列表的变化，计算预算金额
function initBudgetWatcher() {
  // watch(state.spareList, () => {
  //   if (!checkSpareForm()) {
  //     return;
  //   }
  //   const total = state.spareList.reduce((pre, cur) => {
  //     return pre + (cur.unitPrice || 0) * (cur.quantity || 0);
  //   }, 0);
  //   state.budget = (total / 100).toFixed(2).toString();
  //   console.log('total:', total);
  //   conditionAttributeChanged();
  // });
  watch(budget, (newValue) => {
    state.budget = (newValue / 100).toFixed(2).toString();
    console.log('total:', newValue);
    conditionAttributeChanged();
  });
}

const budget = computed(() => {
  return state.spareList.reduce((pre, cur) => {
    return pre + (cur.unitPrice || 0) * (cur.quantity || 0);
  }, 0);
});

//资产类型
function checkAssetForm() {
  /**
   * resultList: 填写类容为true，没填写为false
   */
  const resultList: boolean[] = [];

  state.assetList.forEach((item) => {
    //资产名称
    resultList.push(item.assetName && item.assetName?.length > 0 ? true : false);
  });
  //校验每个字段都不空
  return resultList.every((item) => {
    return item;
  });
}

/**
 * 提交审批
 */
function submit() {
  //报修说明
  if (!state.desc || state.desc?.length === 0) {
    showToast({ title: '报事说明字段不能为空', icon: 'error' });
    return;
  }
  //资产类型
  if (!checkAssetForm()) {
    showToast({ title: '添加资产字段不能为空', icon: 'error' });
    return;
  }
  //耗材类型
  if (!checkSpareForm()) {
    showToast({ title: '添加耗材字段不能为空', icon: 'error' });
    return;
  }

  //耗材数量 > 0 预算金额必须填
  if (state.spareList.length > 0 && (!state.budget || state.budget.length === 0)) {
    showToast({ title: '预算金额字段不能为空', icon: 'error' });
    return;
  }

  showLoading();
  ADD_FP_ASSET_REPAIR_RECORD_REQ({
    addFpAssetRepairRecordDtoList: state.assetList,
    addFprProductDtoList: state.spareList.map((item) => {
      return { ...item, id: item.productId };
    }),
    templateCode: params.templateCode, //'c4690445-2075-4325-8a57-6947025789bc'
    flowGraphAddFlow: state.flowGraphAddFlow,
    repairType: state.repairType,
    desc: state.desc,
    budget: state.budget,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      navigateTo({
        url: '/pages/police-security/submit-success/index',
      }).then(() => {
        //清理缓存
        deleteDraft(params.templateCode);
        clearItems();
      });
    }
  });
}

/**
 * 查询审批模版详情
 * @param code 审批模版code
 */
function queryDetail(code: string) {
  showLoading();
  QUERY_FTD_FOR_ADD_FLOW({ code }).then((res) => {
    state.flowGraph = res.flowpathTemplateDto?.flowGraph;
    state.templateId = res.flowpathTemplateDto?.id;
    state.attributes = res.flowpathTemplateDto?.attributes;
    state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    state.conditionAttr = res.flowpathTemplateDto?.conditionAttr;
    //维修类型-设置默认
    state.repairType = state.attributes?.find(
      (item) => item.attributeCode === 'repairType',
    )?.attributeDefault;
    if (params.id) {
      queryApprovedDetail(params.id);
    } else {
      queryDraft(code);
    }
  });
}

onBeforeUnmount(() => {
  clearItems();
});

onMounted(() => {
  queryContractList();
});
function saveDraft() {
  if (state.userId) {
    saveDraftByRequest();
  } else {
    showLoading();
    LOGIN_APP().then((res) => {
      state.userId = res.sysUserDto.id;
      saveDraftByRequest();
    });
  }
}

function saveDraftByRequest() {
  showLoading();
  SAVE({
    userId: state.userId,
    flowpathRecordDto: {
      templateCode: params.templateCode,
      templateId: state.templateId,
      attributes: state.attributes,
    },
    flowGraphAddFlow: state.flowGraphAddFlow,
    repairDesc: state.desc,
    desc: state.budget,
    assetList: state.assetList.map((item) => {
      return {
        assetTypeId: item.assetTypeId,
        assetTypeName: item.assetTypeName,
        assetId: item.assetId,
        assetName: item.assetName,
      } as FlowPathDraftApi.Asset;
    }),
    spareList: state.spareList.map((item) => {
      return {
        productId: item.productId,
        productName: item.productName,
        productSpecName: item.productSpecName,
        quantity: item.quantity,
      } as FlowPathDraftApi.Product;
    }),
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showModal({
        title: '保存草稿成功',
        showCancel: false,
        content: '下次进入申请页面可继续填写表单内容',
      });
    }
  });
}

function queryDraft(code: string) {
  showLoading();
  LOGIN_APP().then((res) => {
    state.userId = res.sysUserDto.id;
    FIND_ONE({ templateCode: code, userId: state.userId }).then((res) => {
      if (res.flowpathRecordDto) {
        showModal({
          title: '继续填写',
          content: '你有未提交的内容，是否载入草稿继续填写？',
          success: function (result) {
            if (result.confirm) {
              state.attributes = res.flowpathRecordDto?.attributes;
              state.flowGraphAddFlow = res.flowGraphAddFlow;
              state.flowGraph = res.flowGraph;
              state.desc = res.repairDesc;
              state.budget = res.desc || '';
              setDraftData(res.assetList, res.spareList);
              nextTick(() => {
                budgetChange();
                initBudgetWatcher();
              });
            } else if (result.cancel) {
              deleteDraft(code);
              initBudgetWatcher();
            }
          },
        });
      } else {
        initBudgetWatcher();
      }
    });
  });
}

function setDraftData(
  assetList?: FlowPathDraftApi.Asset[],
  spareList?: FlowPathDraftApi.Product[],
) {
  assetList?.forEach((item) => addAssetItemByDraft(item));
  spareList?.forEach((item) => addSpareItemByDraft(item));
}

function deleteDraft(code: string) {
  DELETE({ templateCode: code, userId: state.userId });
}

/**
 * @function 获取审批详情
 */
function queryApprovedDetail(id: string) {
  showLoading();

  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id }).then((res) => {
    setDraftAttributes(res.flowpathRecordDto?.attributes);
    //当界面渲染完成后，否则budget会被spareList值覆盖
    nextTick(() => {
      budgetChange();
      initBudgetWatcher();
    });
  });
}

/**
 * 只修改attribute中的值
 */
function setDraftAttributes(attributes?: FlowPathTemplateApi.AttributeDto[]) {
  const descAttribute = attributes?.find((item) => item.attributeCode === 'desc');
  if (descAttribute) {
    state.desc = descAttribute.attributeValue || '';
    console.log('descAttribute', state.desc);
  }

  //由于资产列表非常多，根据名称无法确定唯一资产
  //信息就不带过去了
  const listAttribute = attributes?.find((item) => item.attributeCode === 'list');
  console.log('listAttribute', listAttribute);

  const productListAttribute = attributes?.find((item) => item.attributeCode === 'productList');
  console.log('productListAttribute', productListAttribute);
  const spareList: FlowPathDraftApi.Product[] = [];
  if (productListAttribute?.attributeValue) {
    spareList.push(...getSpareList(productListAttribute?.attributeValue));
  }
  console.log('spareList', spareList);
  spareList?.forEach((item) => addSpareItemByDraft(item));

  const budgetAttribute = attributes?.find((item) => item.attributeCode === 'budget');
  if (budgetAttribute) {
    state.budget = budgetAttribute.attributeValue || '';
    console.log('budgetAttribute', state.budget);
  }
}

function getSpareList(value: string) {
  const obj: { data?: string[][]; title?: string[] } = JSON.parse(value);
  const spareList: FlowPathDraftApi.Product[] = [];
  obj.data?.forEach((item) => {
    //  "attributeValue": "{\"data\":[],\"title\":[\"耗材品类\",\"规格\",\"数量\"]}",
    const newObj: FlowPathDraftApi.Product = {};
    const product = getProductIdByName(item[0]);
    newObj['productId'] = product?.id || '';
    newObj['productName'] = item[0];
    newObj['productSpecName'] = item[1];
    newObj['quantity'] = parseInt(item[2]);
    spareList.push(newObj);
  });
  return spareList;
}
function getProductIdByName(productName: string) {
  return state.sourceProductList.find((item) => item.productName === productName);
}

/**
 * 查询合同列表
 * useType: 使用类型（1-物品领用，2-报事报修）
 */
function queryContractList() {
  showLoading();
  QUERY_FLOW_PATH_TEMPLATE_CONTRACT({ templateCode: params.templateCode }).then((res) => {
    if (res.queryFlowpathTemplateContractDto && res.queryFlowpathTemplateContractDto.length > 0) {
      const contractId = res.queryFlowpathTemplateContractDto[0].contractId;
      contractId && getProductList(contractId);
    }
  });
}
/**
 * 获取产品列表
 */
function getProductList(contractId: string) {
  QUERY_FPR_PRODUCT_LIST_REQ({ contractId, comQuery: { page: 1, pageSize: 1000 } }).then((res) => {
    state.sourceProductList = res.queryFprProductDtoList || [];
    queryDetail(params.templateCode);
  });
}

/**
 * 个数化数字
 * @param val 原始数字
 */
function formatter(val: string) {
  if (val.indexOf('.') >= 0 && val.slice(val.indexOf('.') + 1).length > 2) {
    //小数个数
    const newValue = val.substring(0, val.indexOf('.') + 1 + 2);
    console.log(newValue);
    return newValue;
  }
  return val;
}

/**
 * 监听所有条件分支属性
 * 当所有条件分支属性填写完成后
 * 触发搜索
 */
function conditionAttributeChanged() {
  // 当所有条件分支属性填写完成后，触发搜索
  const condAttrList = state.attributes?.filter((item) => item.attributeCode === 'budget');
  if (condAttrList && condAttrList.length > 0) {
    condAttrList[0].attributeValue = state.budget;
    showLoading();
    QUERY_FLOW_BY_COND_ATTR({ id: state.templateId, condAttrList }).then((res) => {
      state.flowGraph = res.flowpathTemplateDto?.flowGraph;
      state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    });
  }
}

function budgetChange() {
  if (!state.budget) {
    return;
  }
  conditionAttributeChanged();
}
</script>
<template>
  <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
    <view class="repair-edit__wrapper">
      <nut-form>
        <nut-form-item label="报修事项" required>
          <nut-input
            placeholder="请填写报修事项"
            v-model="state.repairType"
            type="text"
            input-align="right"
            :border="false"
            readonly
          />
        </nut-form-item>
        <nut-form-item label="报修说明" required>
          <nut-textarea
            placeholder="请填写报修说明"
            rows="8"
            limit-show
            text-align="right"
            max-length="200"
            v-model="state.desc"
          />
        </nut-form-item>
      </nut-form>
      <!-- 资产添加 -->
      <asset-type-form class="repair-edit__asset-type" />
      <!-- 耗材添加 --->
      <select-spare />
      <!--申请预算 -->
      <nut-form>
        <nut-form-item label="申请预算" required>
          <nut-input
            placeholder="请填写"
            input-width="50"
            type="digit"
            input-align="right"
            v-model="state.budget"
            :formatter="formatter"
            format-trigger="onChange"
            @blur="budgetChange()"
            :border="false"
          />
        </nut-form-item>
      </nut-form>
      <!-- 流程图 -->
      <nut-cell-group
        v-if="state.conditionAttr && state.conditionAttr === 1 && !state.flowGraphAddFlow"
      >
        <nut-cell>
          <template #title>
            <view class="approve-edit__title"> 流程 </view>
            <view class="approve-edit__content"> 必填信息填写后，流程信息自动显示 </view>
          </template>
        </nut-cell>
      </nut-cell-group>
      <approve-process-list
        v-else-if="state.flowGraphAddFlow && Object.keys(state.flowGraphAddFlow).length > 0"
        :flow-graph-add-flow="state.flowGraphAddFlow"
      />
    </view>
  </scroll-view>
  <view class="repair-edit__footer">
    <nut-button class="repair-edit__footer-btn" block color="#bbb" @click="saveDraft()">
      存草稿
    </nut-button>
    <nut-button class="repair-edit__footer-btn" block type="info" @click="submit()">
      提交
    </nut-button>
  </view>
</template>
<style lang="scss">
.repair-edit {
  &__wrapper {
    padding: 20px 20px;
  }
  &__asset-type {
    margin-bottom: 20px;
  }
  &__footer {
    padding: 20px 20px;
    background-color: #fff;
    display: flex;
  }
  &__footer-btn {
    flex: 1;
    margin: 0 10px;
  }
}
</style>
